package com.dctp.ems.controller;

import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.dctp.common.controller.BaseController;
import com.dctp.common.utils.DateUtil;
import com.dctp.common.vo.JsonResult;
import com.jfinal.core.Path;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.upload.UploadFile;

import java.io.File;
import java.nio.file.Files;
import java.util.Map;
import java.util.UUID;

import static com.dctp.common.vo.TipCode.UPLOAD_FAIL;

@Path("/upload")
public class UploadController extends BaseController {
    // Cloudflare R2/S3 配置
    private static final String ACCESS_KEY = "4c7a16cdeaf30d89be0e55732141e515";
    private static final String SECRET_KEY = "44e70cdf7b3338f341d96223106c1aaee2315bd2556367e92d3492802072c253";
    private static final String BUCKET_NAME = "dctp-bucket";
    private static final String R2_ENDPOINT = "https://58d18639a4e80800a7ca71fc87fd082c.r2.cloudflarestorage.com";  // R2 Endpoint

//    private static final String CDN_DOMAIN = "https://cdn.dctptrader01.com";

    private static String CDN_DOMAIN = "https://dctptrader.com";


//    public void file() {
//
//        // 1. 获取上传的文件（假设是 uni.uploadFile 或 form 表单上传）
//        UploadFile uf = getFile("file"); // "file" 字段
//        if (uf == null) {
//            renderJson(JsonResult.fail(UPLOAD_FAIL));
//            return;
//        }
//        String fileName = uf.getFileName();
//        String subfix = fileName.substring(fileName.lastIndexOf("."));
//        String prefix = getPara("prefix");
//        String newFileName = String.format("%s-%d%s", prefix, System.currentTimeMillis(), subfix);
//        File localFile = uf.getFile();
//        try {
//            // 2. 初始化 S3/R2 客户端
////            AmazonS3 s3 = AmazonS3ClientBuilder.standard()
////                .withEndpointConfiguration(new AmazonS3ClientBuilder.EndpointConfiguration(R2_ENDPOINT, "auto"))
////                .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY)))
////                .withPathStyleAccessEnabled(true) // R2 必须
////                .build();
//
//            // 3. 上传文件到 R2
//
//            //String key = "uploads/" + System.currentTimeMillis() + "_" + fileName;
//            //s3.putObject(BUCKET_NAME, key, localFile);
//            // 4. 返回R2文件访问路径（如有CDN可拼CDN）
//
//            // 4. 复制到本地目录
//            File localDir = new File("/data/upload/images/admin/");
//            if (!localDir.exists()) {
//                localDir.mkdirs();
//            }
//            File serverFile = new File(localDir, newFileName);
//            // 覆盖同名文件
//            Files.copy(localFile.toPath(), serverFile.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING);
//            String url = CDN_DOMAIN + "/images/admin/" + newFileName;
//            renderJson(JsonResult.successWithData(Map.of("url", url)));
//        } catch (Exception e) {
//            e.printStackTrace();
//            renderJson(JsonResult.fail(UPLOAD_FAIL));
//        } finally {
//            // 5. 删除临时文件
//            uf.getFile().delete();
//        }
//    }


    public void file() {

        UploadFile uf = getFile("file"); // "file" 字段
        if (uf == null) {
            renderJson(JsonResult.fail(UPLOAD_FAIL));
            return;
        }

        Prop p = PropKit.use("project.properties");
        if (!"prod".equals(p.get("env"))) {
            CDN_DOMAIN = "https://traderder.com";
        }

        // 原始文件名
        String originalFileName = uf.getOriginalFileName();
        // 用 UUID 生成安全文件名
        String fileName = uf.getFileName();
        String subfix = fileName.contains(".")
                ? fileName.substring(fileName.lastIndexOf("."))
                : ""; // 没有后缀也能正常处理
        String prefix = getPara("prefix", "file"); // 默认 file
        // ✅ 文件名仅保留英文 + 数字，避免中文/空格问题
        String newFileName = String.format("%s-%d-%s%s",
                prefix,
                getUserId(),
                DateUtil.format(DateUtil.now(), "yyyyMMddHHmmss"),
                subfix
        );
        // 改名（JFinal 默认保存的位置直接覆盖）
        uf.getFile().renameTo(new File(uf.getUploadPath(), newFileName));

        // 返回文件访问路径
        String url = CDN_DOMAIN + "/images/admin/" + newFileName;
        renderJson(JsonResult.successWithData(Map.of(
                "url", url,
                "originalName", originalFileName)));  // ✅ 可选：保留原始中文名给前端展示
    }
}
